package cn.yuanqiao.archive.bianyan.service.Impl;

import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.bianyan.domain.*;
import cn.yuanqiao.archive.bianyan.mapper.SpecialSubjectContenrMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZhuanTiMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZhuantiChengguoMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZtcgFileMapper;
import cn.yuanqiao.archive.bianyan.service.ISpecialSubjectContenrService;
import cn.yuanqiao.archive.management.utils.FileUtil;
import cn.yuanqiao.archive.utils.ImageUtils;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.uuid.Seq;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.commons.io.FilenameUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import static cn.yuanqiao.archive.collection.appManager.service.impl.YqDataCategoryServiceImpl.log;
/**
 * 专题统稿内容Service业务层处理
 * 
 * @author xy
 * @date 2023-09-13
 */
@Service
public class SpecialSubjectContenrServiceImpl implements ISpecialSubjectContenrService 
{
    @Autowired
    private SpecialSubjectContenrMapper specialSubjectContenrMapper;

    @Autowired
    private YqZhuanTiMapper yqZhuanTiMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    @Autowired
    private YqZtcgFileMapper yqZtcgFileMapper;


    @Autowired
    private YqZhuantiChengguoMapper yqZhuantiChengguoMapper;


    /**
     * 查询专题统稿内容
     * 
     * @param id 专题统稿内容主键
     * @return 专题统稿内容
     */
    @Override
    public SpecialSubjectContenr selectSpecialSubjectContenrById(Long typeId)
    {
        SpecialSubjectContenr specialSubjectContenr= specialSubjectContenrMapper.selectSpecialSubjectContenrById(typeId,new SpecialSubjectContenr().getTableName());
        String tableNameZt = SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUAN_TI;
        YqZhuanTi yqZhuanTi=yqZhuanTiMapper.selectZhuanTiByTypeId(typeId+"",tableNameZt);
        if(specialSubjectContenr!=null) {
            specialSubjectContenr.setArchiveIds(yqZhuanTi.getArchiveIds() == null ? "" : yqZhuanTi.getArchiveIds());
            specialSubjectContenr.setMaterialIds(yqZhuanTi.getMaterialIds() == null ? "" : yqZhuanTi.getMaterialIds());
            specialSubjectContenr.setCategoryIds(yqZhuanTi.getCategoryIds() == null ? "" : yqZhuanTi.getCategoryIds());
        }
        return specialSubjectContenr;
    }

    /**
     * 查询专题统稿内容列表
     * 
     * @param specialSubjectContenr 专题统稿内容
     * @return 专题统稿内容
     */
    @Override
    public List<SpecialSubjectContenr> selectSpecialSubjectContenrList(SpecialSubjectContenr specialSubjectContenr)
    {
        return specialSubjectContenrMapper.selectSpecialSubjectContenrList(specialSubjectContenr);
    }

    /**
     * 新增专题统稿内容
     * 
     * @param specialSubjectContenr 专题统稿内容
     * @return 结果
     */
    @Override
    public int insertSpecialSubjectContenr(SpecialSubjectContenr specialSubjectContenr)
    {
        //判断该值是否存在，存在的话则就行修改
        SpecialSubjectContenr specialSubject=specialSubjectContenrMapper.selectSpecialSubjectContenrById(specialSubjectContenr.getTypeId(),new SpecialSubjectContenr().getTableName());
        //修改状态
        String tableNameZt = SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUAN_TI;
        YqZhuanTi yqZhuanTi=yqZhuanTiMapper.selectZhuanTiByTypeId(specialSubjectContenr.getTypeId()+"",tableNameZt);
        yqZhuanTi.setState(specialSubjectContenr.getState());
        /**
         * 状态 0：未编辑 1：编辑中 2：编辑完成 3：统稿中 4：统稿完成
         */
        if("1".equals(specialSubjectContenr.getIsKeep())){
           yqZhuanTi.setArchiveIds(specialSubjectContenr.getArchiveIds());
           yqZhuanTi.setMaterialIds(specialSubjectContenr.getMaterialIds());
           yqZhuanTi.setCategoryIds(specialSubjectContenr.getCategoryIds());


        }else if("0".equals(specialSubjectContenr.getIsKeep())){
           yqZhuanTi.setArchiveIds("");
           yqZhuanTi.setMaterialIds("");
           yqZhuanTi.setCategoryIds("");
          }
        int count=yqZhuanTiMapper.updateZhuanTi(yqZhuanTi,tableNameZt);
        if(specialSubject!=null){
            //修改内容
            specialSubjectContenr.setId(specialSubject.getId());
              if(specialSubjectContenr.getContent()==null&&specialSubjectContenr.getManuscript()==null){
                  return count;
              } else {
                  return specialSubjectContenrMapper.updateSpecialSubjectContenr(specialSubjectContenr);
              }
        }else {
            return specialSubjectContenrMapper.insertSpecialSubjectContenr(specialSubjectContenr);
        }
    }

    /**
     * 修改专题统稿内容
     * 
     * @param specialSubjectContenr 专题统稿内容
     * @return 结果
     */
    @Override
    public int updateSpecialSubjectContenr(SpecialSubjectContenr specialSubjectContenr)
    {
        return specialSubjectContenrMapper.updateSpecialSubjectContenr(specialSubjectContenr);
    }

    /**
     * 批量删除专题统稿内容
     * 
     * @param ids 需要删除的专题统稿内容主键
     * @return 结果
     */
    @Override
    public int deleteSpecialSubjectContenrByIds(Long[] ids)
    {
        return specialSubjectContenrMapper.deleteSpecialSubjectContenrByIds(ids);
    }

    /**
     * 删除专题统稿内容信息
     * 
     * @param id 专题统稿内容主键
     * @return 结果
     */
    @Override
    public int deleteSpecialSubjectContenrById(Long id)
    {
        return specialSubjectContenrMapper.deleteSpecialSubjectContenrById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int achievement(Long ids, String mj) {
        int num = 0;
        try {
            List<YqZhuanTi> list = yqZhuanTiMapper.selectYqZhuanTiTree(ids, SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUAN_TI, SecurityUtils.getTenantCode().toUpperCase());
            int count = yqZhuanTiMapper.selectYqZhuanTiTreeByState(ids, SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUAN_TI, SecurityUtils.getTenantCode().toUpperCase());

            if (list.size() > count) {
                throw new ServiceException("所选数据中含有未统稿的专题,不能转至专题成果！");
            }
            String path = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
            if (StringUtils.isEmpty(path)) {
                throw new ServiceException("YQ_ZT_PATH的值不能为空！");
            }

            int cgCount = yqZhuantiChengguoMapper.getCountByTypeId(ids, SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUANTI_CHENGUO);
            if (cgCount > 0) {
                throw new ServiceException("该专题已转至成果管理！");
            }

            String clobdatas = "";
            List<YqZhuantiChengguo> yqZhuantiChengguoList = new ArrayList<>();
            List<YqZtcgFile> yqZtcgFileList = new ArrayList<>();

            String tableNameZt = SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_ZHUAN_TI;
            YqZhuanTi zhuanTi = yqZhuanTiMapper.selectZhuanTiByTypeId(ids + "", tableNameZt);

            List<YqZhuanTi> zhuantiList = yqZhuanTiMapper.selectYqZhuanTiTree(ids, tableNameZt, SecurityUtils.getTenantCode().toUpperCase());
            for (int i = 0; i < zhuantiList.size(); i++) {
                YqZhuanTi yqZhuanTi = zhuantiList.get(i);

                String typeName = yqZhuanTi.getTypeName();
                SpecialSubjectContenr specialSubjectContenr = specialSubjectContenrMapper.selectSpecialSubjectContenrById(Long.parseLong(yqZhuanTi.getTypeId()), new SpecialSubjectContenr().getTableName());
                String manuscript = specialSubjectContenr.getManuscript();
                String s = i + 1 + ": " + typeName;
                if (!"".equals(manuscript)) {
                    clobdatas += "<p><br/></p><p><strong>目录" + s + "</strong></p>" + manuscript;
                }

                String tmpContent = clobdatas;
                tmpContent = tmpContent.replaceAll("class=\"ql-align-center\"", "style=\"text-align: center\"");
                Document document = Jsoup.parse(tmpContent);
                Elements img = document.getElementsByTag("img");
                int index = 0;
                List<String> imgBase64List = new ArrayList<>();
                for (Element element : img) {
                    imgBase64List.add(element.attr("src"));
                    String attrData = element.attr("src");
                    attrData = attrData.replaceAll("\\+", "\\\\+");
                    tmpContent = tmpContent.replaceAll(attrData, "{{image_src" + index + "}}");
                    index++;
                }

                index = 0;
                String prefix = "data:image/png;base64,";
                for (String base64 : imgBase64List) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(base64)) {
                        byte[] imageBytes = ImageUtils.downloadImage(base64);
                        base64 = Base64.getEncoder().encodeToString(imageBytes);
                        base64 = base64.replaceAll(prefix, "");
                        BufferedImage bufferedImage = ImageUtils.bytesToBufferedImage(ImageUtils.base64ToByte(base64));
                        if (bufferedImage == null) {
                            tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", "");
                        } else {
                            int height = bufferedImage.getHeight();
                            int width = bufferedImage.getWidth();
                            if (width > 650) {
                                height = (int) (height * 650.0 / width);
                                BufferedImage imgZoom = ImageUtils.resizeImage(bufferedImage, 700, height);
                                String imageToBase64 = ImageUtils.imageToBase64(ImageUtils.imageToBytes(imgZoom));
                                tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", prefix + imageToBase64);
                            } else {
                                tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", prefix + base64);
                            }
                        }
                    } else {
                        tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", "");
                    }
                    index++;
                }
                clobdatas = tmpContent;
            }
            Long s = System.currentTimeMillis();
            //writerErrorFileContent(path+"CGZCFilePath/",zhuantiName+"_"+s+".doc",list);
            //将clobdata数据写入服务器指定路径下
//            String content="Mime-Version: 1.0\n" +
//                    "Content-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n" +
//                    "\n" +
//                    "--NEXT.ITEM-BOUNDARY\n" +
//                    "Content-Type: text/html; charset=\"utf-8\"\n"+
//                    "\n";
//
            StringBuilder content = new StringBuilder();
            content.append("<html " +
                    "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\"" + //将版式从web版式改成页面试图
                    ">");
            content.append("<head>" +
                    "<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->" +
                    "</head>");
            content.append("<body>");
            content.append(clobdatas);
            content.append("</body></html>");

            ByteArrayInputStream inputStream = new ByteArrayInputStream(content.toString().getBytes("GBK"));
            FileUtil fileUtil = new FileUtil();
            String fileName = zhuanTi.getTypeName() + SecurityUtils.getTenantCode() + s + ".doc";
            fileName = StringUtils.format("{}/{}/{}.{}", DateUtils.datePath(), Seq.getId(Seq.uploadSeqType),
                    FilenameUtils.getBaseName(fileName), "doc");
            File file = new File(path + fileName);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
            }
            fileUtil.outPutFileToPath(inputStream, path + fileName);
            inputStream.close();

            String id = SnowflakeIdGenerator.generateId() + "";
            YqZhuantiChengguo yqZhuantiChengguo = new YqZhuantiChengguo();
            yqZhuantiChengguo.setChengguoId(id);
            yqZhuantiChengguo.setChengguoName(zhuanTi.getTypeName());
            yqZhuantiChengguo.setCreatorId(SecurityUtils.getUserId().toString());
            yqZhuantiChengguo.setCREATOR(SecurityUtils.getLoginUser().getSysUser().getNickName());
            yqZhuantiChengguo.setCreateTime(DateUtils.getNowDate());
            yqZhuantiChengguo.setIsDel("0");
            yqZhuantiChengguo.setPublishType("2");
            yqZhuantiChengguo.setIssueState("0");
            yqZhuantiChengguo.setUnitName(SecurityUtils.getLoginUser().getSysUser().getDept().getDeptName());
            yqZhuantiChengguo.setTypeId(ids);
            yqZhuantiChengguo.setMj(mj);
            yqZhuantiChengguoList.add(yqZhuantiChengguo);

            String fileId = SnowflakeIdGenerator.generateId() + "";
            yqZhuantiChengguo.setUnitName(SecurityUtils.getLoginUser().getSysUser().getDept().getDeptName());
            YqZtcgFile yqZtcgFile = new YqZtcgFile();
            yqZtcgFile.setFileId(fileId);
            yqZtcgFile.setFileName(fileName);
            yqZtcgFile.setChengguoId(id);
            yqZtcgFile.setFilePath(fileName);
            yqZtcgFile.setFileSize(file.length() + "");
            yqZtcgFileList.add(yqZtcgFile);

            String code = SecurityUtils.getTenantCode().toUpperCase();
            num += yqZtcgFileMapper.insertYqZtcgFile(yqZtcgFileList, code + Constants.TABLE_YQ_ZTCG_FILE);
            num += yqZhuantiChengguoMapper.insertYqZhuantiChengguoList(yqZhuantiChengguoList, code + Constants.TABLE_YQ_ZHUANTI_CHENGUO);
        } catch (ServiceException serviceException) {
            log.error("ServiceException occurred: {}", serviceException.getMessage(), serviceException);
            throw new ServiceException(serviceException.getMessage());
        } catch (Exception e){
            log.error("写入文件失败！", e);
            throw new ServiceException("写入文件失败！");
        }
        return num;

    }

    @Override
    public List<SourceMaterial> sourceMaterialList(SpecialSubjectContenr specialSubjectContenr) {
       String archiveIds=specialSubjectContenr.getArchiveIds();
       String materialIds=specialSubjectContenr.getMaterialIds();
       String code=SecurityUtils.getTenantCode().toUpperCase();
       List<SourceMaterial>sourceMaterialList=new ArrayList<>();
       if(!StringUtils.isEmpty(archiveIds)){
           //说明有值
           String[] archiveIdArr=archiveIds.split(",");
           for(String daId:archiveIdArr){
             //通过档案Id 获取文件表
               String efileTableName=specialSubjectContenrMapper.getFileTableName(code,daId);
                if(!StringUtils.isEmpty(efileTableName)) {
                    String categoryId = specialSubjectContenrMapper.getCategoryId(code, daId);
                    //通过efileTableName以及档案Id获取文件相关数据
                    List<SourceMaterial> sourceMaterial = specialSubjectContenrMapper.selectSourceMaterialByDaId(efileTableName, daId, categoryId);
                    sourceMaterialList.addAll(sourceMaterial);
                }
           }

       }
        if(!StringUtils.isEmpty(materialIds)){
            String tableName = SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_DATA_GEREN_KU;
            List<SourceMaterial> list=specialSubjectContenrMapper.selectSourceMaterialByMaterialIds(materialIds,tableName);
            sourceMaterialList.addAll(list);
        }

        return sourceMaterialList;
    }

    @Override
    public List<SourceMaterial> getSourceMaterialList(SpecialSubjectContenr specialSubjectContenr) {
        String archiveIds=specialSubjectContenr.getArchiveIds();
        String categoryIds=specialSubjectContenr.getCategoryIds();
        String materialIds=specialSubjectContenr.getMaterialIds();
        String code=SecurityUtils.getTenantCode().toUpperCase();
        List<SourceMaterial>sourceMaterialList=new ArrayList<>();
        if(!StringUtils.isEmpty(archiveIds)){
            //说明有值
            String[] archiveIdArr=archiveIds.split(",");
            String [] categoryIdArr=categoryIds.split(",");
            for(int i=0;i<archiveIdArr.length;i++){
                //通过档案Id 获取文件表
                String docId=archiveIdArr[i];
                String categoryId=categoryIdArr[i];
                String efileTableName=specialSubjectContenrMapper.getFileTableNameByCategoryId(code,categoryId);

/*
                Long categoryId=specialSubjectContenrMapper.getCategoryId(code,daId);
*/
                //通过efileTableName以及档案Id获取文件相关数据
                if(!StringUtils.isEmpty(efileTableName)) {
                    SourceMaterial sourceMaterial = specialSubjectContenrMapper.selectSourceMaterialByDocId(efileTableName, docId, Long.valueOf(categoryId));
                    sourceMaterialList.add(sourceMaterial);
                }
            }

        }
        if(!StringUtils.isEmpty(materialIds)){
            String tableName = SecurityUtils.getTenantCode().toUpperCase() + Constants.TABLE_YQ_DATA_GEREN_KU;
            List<SourceMaterial> list=specialSubjectContenrMapper.selectSourceMaterialByMaterialIds(materialIds,tableName);
            sourceMaterialList.addAll(list);
        }

        return sourceMaterialList;
    }

    @Override
    public TenantYqdaDocument viewByDocid(Long doc_id, String efiletable) {
        return specialSubjectContenrMapper.viewByDocid(doc_id,efiletable);
    }
}
